package com.pvdnc.riru.appinjector.nuwa;

import android.util.Log;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class ArrayUtils {
    private static final String TAG=ArrayUtils.class.getSimpleName();

    public static Object removeSubArray(Object all,Object sub){
        int allLength= Array.getLength(all);
        int subLength=Array.getLength(sub);
        List resultList=new ArrayList();
        for (int subIndex = 0; subIndex < subLength; subIndex++) {
            Object subItem=Array.get(sub,subIndex);
            for (int allIndex = 0; allIndex < allLength; allIndex++) {
                Object allItem=Array.get(all,allIndex);
                if(subItem.equals(allItem))
                    continue;
                resultList.add(allItem);
            }
        }
        Log.d(TAG,"result list:\n\t"+resultList);
        Class<?> componentClass=all.getClass().getComponentType();
        int remainLength=resultList.size();
        Object resultArray=Array.newInstance(componentClass,remainLength);
        for (int i = 0; i < remainLength; i++) {
            Array.set(resultArray,i,resultList.get(i));
        }

        return resultArray;
    }

    public static Object combineArray(Object firstArray, Object secondArray) {
        Class<?> localClass = firstArray.getClass().getComponentType();
        int firstArrayLength = Array.getLength(firstArray);
        int allLength = firstArrayLength + Array.getLength(secondArray);
        Object result = Array.newInstance(localClass, allLength);
        for (int k = 0; k < allLength; ++k) {
            if (k < firstArrayLength) {
                Array.set(result, k, Array.get(firstArray, k));
            } else {
                Array.set(result, k, Array.get(secondArray, k - firstArrayLength));
            }
        }
        return result;
    }
}
